package com.shiyang.seckill.controller;

import com.shiyang.seckill.redis.UserKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shiyang.seckill.domain.User;
import com.shiyang.seckill.redis.RedisService;
import com.shiyang.seckill.result.CodeMsg;
import com.shiyang.seckill.result.Result;
import com.shiyang.seckill.service.UserService;

/**
 * @author shiyang date: 2020/7/16
 */
// 这里必须使用controller才能通过hello映射到hello.html restcontroller不可以
@Controller
@RequestMapping("/demo")
public class SampleController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    @ResponseBody
    @RequestMapping("/home")
    public String home() {
        return "hello world";
    }

    // 跳页面的话就不能用@ResponseBody了 它返回的结果只能是String
    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model) {
        model.addAttribute("name", "shiyang");
        return "hello";
    }

    /**
     * Controller中的方法一般分为两大类 1. Rest API json输出 2. 页面
     */
    @RequestMapping("/hello")
    @ResponseBody
    public Result<String> hello() {
        return Result.success("hello seckill");
    }

    @RequestMapping("/error")
    @ResponseBody
    public Result<String> error() {
        return Result.error(CodeMsg.SERVER_ERR);
    }

    @RequestMapping("/get")
    @ResponseBody
    public Result<User> get() {
        User user = userService.getById(1);
        return Result.success(user);
    }

    @RequestMapping("transaction")
    @ResponseBody
    public Result<Boolean> transaction() {
        boolean b = userService.transaction();
        return Result.success(true);
    }

    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet() {
        User user = redisService.get(UserKey.getById, ""+1, User.class);
        return Result.success(user);
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        User user = new User();
        user.setId(1);
        user.setName("changsha");
        boolean result = redisService.set(UserKey.getById, "" + 1, user);
        return Result.success(result);
    }
}
